package com.test.SocketDemo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * ${DESCRIPTION}
 *
 * @author muxiaoyu
 * @create 2017/06/08 11:01
 **/
public class RemoteFileClient {
    protected String hostIp;
    protected int hostPort;
    protected BufferedReader socketReader;
    protected PrintWriter socketWriter;

    public RemoteFileClient(String aHostIp, int aHostPort) {
        this.hostIp = aHostIp;
        this.hostPort = aHostPort;
    }

    public static void main(String[] args) {
        RemoteFileClient remoteFileClient = new RemoteFileClient("172.16.4.205", 3000);
        remoteFileClient.setUpConnection();
        String fileContents = remoteFileClient.getFile("D:\\1.dat");
        System.out.println(fileContents);
        remoteFileClient.tearDownConnection();
    }

    public void setUpConnection() {
        try {
            Socket client = new Socket(hostIp, hostPort);
            socketReader = new BufferedReader(new InputStreamReader(client.getInputStream()));
            socketWriter = new PrintWriter(client.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public String getFile(String fileNameToGet) {
        StringBuffer stringBuffer = new StringBuffer();
        try {
            socketWriter.println(fileNameToGet);
            socketWriter.flush();
            String line;
            while ((line = socketReader.readLine()) != null) {
                stringBuffer.append(line + "\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return stringBuffer.toString();
    }

    public void tearDownConnection() {
        try {
            socketWriter.close();
            socketReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
